package com.amado.easyui2.servlet;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.amado.easyui2.domain.StudentEntity;
import com.amado.easyui2.exception.ApiException;
import com.amado.easyui2.service.StudentService;
import com.amado.easyui2.util.ArrayUtil;
import com.amado.easyui2.util.DateUtil;
import com.amado.easyui2.util.ExcelUtil;
import com.amado.easyui2.util.JsonUtil;
import com.amado.easyui2.util.SessionUtils;
import com.amado.easyui2.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;

public class StudentServlet extends HttpServlet {
	StudentService studentService;
	private static final long serialVersionUID = 1L;
	private static ObjectMapper mapper = new ObjectMapper();
//    private DriverManagerDataSource dataSource;
	ApplicationContext applicationContext;

	@Override
	public void init() throws ServletException {
		// Spring容器
		applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
		// 通过容器获取Bean
		studentService = applicationContext.getBean("studentServcieImpl", StudentService.class);
	}

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setCharacterEncoding("UTF-8");
		String method = arg0.getParameter("method");
		if ("add".equals(method)) {
			add(arg0, arg1);
		} else if ("delete".equals(method)) {
			delete(arg0, arg1);
		} else if ("edit".equals(method)) {
			edit(arg0, arg1);
		} else if ("update".equals(method)) {
			update(arg0, arg1);
		} else if ("query".equals(method)) {
			query(arg0, arg1);
		} else if ("export".equals(method)) {
			export(arg0, arg1);
		}
	}

	private void add(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		try {
		String strJson = arg0.getParameter("data");
		StudentEntity student = JsonUtil.jsonToBean(strJson, StudentEntity.class);
		student.setCreateName(SessionUtils.getUserName(arg0));
		studentService.addStudent(student);
		arg1.getWriter().print(JsonUtil.beanToJson(new Result()));
		}catch (ApiException e) {
			arg1.getWriter().print(JsonUtil.beanToJson(new Result(e.getCode(),e.getMessage())));
		}
	}

	private void delete(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		String ids = arg0.getParameter("ids");
		if (ids != null && ids.trim() != "") {
			String[] stringIdArray = ids.split(",");
			Long[] longIdArray = ArrayUtil.StringToInt(stringIdArray);
			studentService.deleteStudent(longIdArray);
			arg1.getWriter().print(JsonUtil.beanToJson(new Result()));
		} else {
			arg1.getWriter().print(JsonUtil.beanToJson(new Result("0", "参数错误")));
		}

	}

	private void edit(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Long id = Long.valueOf(arg0.getParameter("id"));
		StudentEntity student = studentService.getById(id);
		PrintWriter out = arg1.getWriter();
		out.print(mapper.writeValueAsString(student));
		/*
		 * List<StudentEntity> list = studentService.listAll(); for (StudentEntity user
		 * : list) { if (user.getId().equals(id)) { StudentEntity userId = user;
		 * PrintWriter out = arg1.getWriter();
		 * out.print(mapper.writeValueAsString(userId)); break; } }
		 */
	}

	private void update(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		String strJson = arg0.getParameter("data");// 解析
		StudentEntity student = JsonUtil.jsonToBean(strJson, StudentEntity.class);
		studentService.updateStudent(student);
//		String strJson = arg0.getParameter("data");// 解析
//		User userInfo = JsonUtil.jsonToBean(strJson, User.class);
//		Long id = userInfo.getId();
//		String departmentNum = userInfo.getDepartmentNum();
//		String userNum = userInfo.getUserNum();
//		String password = userInfo.getPassword();
//		String createName = userInfo.getCreateName();
//		String updateName = userInfo.getUpdateName();
//		User user = new User(id, departmentNum, userNum, password, createName, updateName);
//		userService.update(user);
		arg1.getWriter().print(JsonUtil.beanToJson(new Result()));

	}

	private void query(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		String name = arg0.getParameter("name");
		String idNumber = arg0.getParameter("idNumber");
		List<StudentEntity> shopList = studentService.listAll(name, idNumber);
		PrintWriter out = arg1.getWriter();
		out.print(mapper.writeValueAsString(shopList));
	}

	private void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		String excelName = "学员信息表";
		response.addHeader("Content-Disposition",
				"attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");
		String[] headers = new String[] { "id", "姓名", "身份证号码", "性别", "年龄", "手机", "住址", "户籍", "报考车型", "学费", "报名时间",
				"创建人" };

		List<StudentEntity> list = studentService.listAll(null, null);
		List<List<String>> resultList = new ArrayList<>();
		for (StudentEntity student : list) {
			resultList.add(Arrays.asList(String.valueOf(student.getId()), student.getName(), student.getIdNumber(),
					student.getSex(), student.getAge(), student.getPhone(), student.getAddress(),
					student.getCensusRegister(), student.getCandiCar(), student.getLearnSalary(),
					DateUtil.parseDateToStr(student.getApplyTime(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS), student.getCreateName()));
		}

		try {
			OutputStream out = response.getOutputStream();
			ExcelUtil.exportExcel("学员", headers, resultList, out);
			System.out.println("excel导出成功！");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
